﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;

namespace ProgNetComponents.Design.TypeConverters
{
    public class ArrayTypeConverter<T> : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                List<T> l = new List<T>();
                string[] v = ((string)value).Split(new char[] { ';' });
                try
                {
                    foreach (string s in v)
                    {
                        l.Add((T)(Convert.ChangeType(s.Trim(), typeof(T))));
                    }
                    return l.ToArray();
                }
                catch { }
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                string str = "";
                if (value is T[])
                {
                    foreach (T i in ((T[])(value)))
                        str += i.AsString() + ";";
                }
                return str.TrimEnd(';');
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
